<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <NSpace>
              <NForm ref="formRef" :model="formValue" label-placement="left" :label-width="100" label-align="right"
                :rules="rules" require-mark-placement="left">
                <NFormItem label="标题:" path="title">
                  <NInput v-model:value="formValue.title" :allow-input="stopNull" placeholder="请输入标题" class="commonWidth"
                    clearable />
                </NFormItem>
                <NFormItem label="是否启用:" path="status">
                  <NSelect class="commonWidth" placeholder="请选择图片状态" :options="statusList"
                    v-model:value="formValue.status" clearable />
                </NFormItem>
                <NFormItem label="图片上传:" path="fileId">
                  <VUpload :file-list="fileList" @getList="handleUploadList" :typeAccept="typeAccept"
                    :disabled="disabledImg" />
                </NFormItem>
                <NFormItem label="缩略图:" v-if="returnImg?.length">
                  <NImage width="300" :src="returnImg" />
                </NFormItem>
              </NForm>
            </NSpace>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton ghost @click="goBack">
        取消
      </NButton>
      <NButton type="primary" @click="confirm">
        保存
      </NButton>
    </NSpace>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againConfirm" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要保存吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NSpin,
  useMessage,
  NModal,
  NImage,
  NSelect
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import VUpload from '@/views/OA/Common/Upload.vue'
import type { FormRules } from 'naive-ui'

const message = useMessage()
const route = useRoute()
const tags = useTagStore().tags

const props = defineProps({
  title: { type: String, default: () => '新增党建轮播图' }
})

const typeAccept: any = 'image/*'

const formRef = ref<FormInst | null>(null)
const formValue = reactive<Record<string, any>>({
  title: null,
  status: null,
  fileId: null
})

const rules: FormRules = {
  title: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入标题')
      if (value?.length > 100) return new Error('标题不得超过100字')
      return true
    }
  },
  status: {
    required: true,
    message: '请选择状态',
    trigger: ['input', 'blur']
  },
  fileId: {
    required: true,
    message: '图片不能为空',
    trigger: ['input', 'blur']
  },
}

//去除空格
const stopNull = (value: string) => {
  return !value.startsWith(' ') && !value.endsWith(' ')
}

//状态下拉
const statusList = [
  {
    value: '1',
    label: '是'
  },
  {
    value: '0',
    label: '否'
  }
]

//回显信息
const spinShow = ref(false)
const getInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'partAffairs',
    api: 'imgItem',
    uri: {
      id: route.query.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code != 0) return message.error(res.msg)
  fileList.value = [res.data?.sysAnnexFile]
  if (fileList.value.length) {
    disabledImg.value = true
  } else {
    disabledImg.value = false
  }
  Object.keys(formValue).map((it: any) => {
    if (it == 'status') {
      formValue.status = res.data.status.toString()
    } else {
      // @ts-ignore
      formValue[it] = res.data[it]
    }
  })
  spinShow.value = false
}

// 附件
const fileList: any = ref([])
const disabledImg = ref(false)
const handleUploadList = (v: any) => {
  formValue.fileId = v
  if (v) {
    disabledImg.value = true
  } else {
    disabledImg.value = false
  }
}

// 获取详情
const returnImg = ref()
const getFJInfo = async () => {
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'fjInfo',
    uri: {
      id: formValue.fileId
    }
  })
  if (error) return
  if (res.code !== 0) return
  returnImg.value = res.data.path
}

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.fullPath === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  history.back()
}
// 确定
const modalVisible = ref(false)
const confirm = () => {
  formRef.value?.validate(async (err: any) => {
    if (err) return
    modalVisible.value = true
  })
}

const againConfirm = async () => {
  if (route.path == '/OA/Affairs/ImgEdit') {
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'partAffairs',
      api: 'imgUpdate',
      override: {
        data: {
          id: route.query.id,
          ...formValue
        }
      }
    })
    if (error) return message.error(error.message)
    message.success(res.msg)
    goBack()
  } else {
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'partAffairs',
      api: 'imgSave',
      override: {
        data: {
          ...formValue
        }
      }
    })
    if (error) return message.error(error.message)
    message.success(res.msg)
    goBack()
  }
  modalVisible.value = false
}

watch(
  () => formValue.fileId,
  () => {
    if (formValue.fileId) {
      getFJInfo()
    } else {
      returnImg.value = null
    }
  }
)

watch(
  () => route,
  () => {
    if (route.path == '/OA/Affairs/ImgEdit' && route.query.id) getInfo()
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        width: 360rem;
        height: 130rem;
        background: #e1e1e1;
        margin-bottom: 25rem;
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
